const Danmu = require('./../models/danmuModel');
const Video = require('./../models/videoModel');
const catchAsync = require('./../utils/catchAsync.js');
const AppError = require('./../utils/appError.js');
const APIFeatures = require('./../utils/apiFeatures.js');
const factory = require('./handlerFactory');
exports.setdanmuUserId = (req, res, next) => {
  if (!req.body.user) req.body.user = req.user.id;
  next();
};

// 创建 视频下弹幕的函数（在用户的）
exports.createDanmu = catchAsync(async (req, res, next) => {
  const { user, video, txt, start } = req.body;
  const video1 = await Video.findById(video);
  // 创建弹幕
  const danmu = await Danmu.create({
    txt: txt,
    start: start,
    video: video,
    user: user,
  });

  if (!video1) {
    return next(new AppError('video not found', 404));
  }
  if (!video1.danmus || !Array.isArray(video1.danmus)) {
    video1.danmus = []; // 如果不存在或者不是数组，可以进行初始化
  }
  // 将 弹幕 添加到视频中
  video1.danmus.push(danmu._id);
  await video1.save();
  // 将videoReview添加到当前video的评论 列表中
  // 假设你的用户模型是 User，可以通过 userId 找到当前用户
  // await userU.save();
  res.status(200).json({
    status: 'success',
    danmu,
    message: 'danmu added to video successfully',
  });
});

//获取视频下所有弹幕的函数
exports.getAllDanmus = catchAsync(async (req, res, next) => {
  const { user, video } = req.body;
  const video1 = await Video.findById(video);
  if (!video1) {
    return next(new AppError('video not found', 404));
  }

  res.status(200).json({
    status: 'success',
    danmusList: video1.danmus,
    message: 'danmusList is above',
  });
});
// exports.getAlldanmus = factory.getAll(Danmu);

exports.getdanmu = factory.getOne(Danmu);
// exports.createdanmu = factory.createOne(Danmu);
exports.updatedanmu = factory.updateOne(Danmu);
exports.deletedanmu = factory.deleteOne(Danmu);
